//首页
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { View, Text, Image, Button, RichText } from '@tarojs/components';
import './index.less';
import TitleBar from 'src/components/titleBar';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import { observer } from 'mobx-react-lite';
import {
  addCollectionFun,
  cancelCollectionFun,
  queryInfoFun,
} from '@/src/common/method/homeFun';
import store from '@/src/store';
import { showToast, StatusToast } from '@/src/components/statusToast';
import { formatRichText, getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';
import CommonBlank from '@/src/components/pageBlank';
import { halfScreenJump } from '@/src/utils/halfScreen';
import { isLoginFun } from '@/src/common/method/commonFun';

interface RouteParams {
  contentId?: string;
  contentKind?: string;
  contentType?: string;
  from?: string;
  [key: string]: string | undefined;
}
let clickAble = true;
//文章详情
const ArticleDetail = () => {
  const { params } = useRouter<RouteParams>();
  const [collect, setCollect] = useState(false); //收藏状态
  const [data, setData] = useState<any>({}); //内容详情
  const [loadingText, setLoadingText] = useState('');
  const [auditStatus, setAuditStatus] = useState<boolean>(false);
  console.error(params.from, 'from========');
  //查询内容详情
  const queryInfoList = () => {
    setLoadingText('加载中...');
    queryInfoFun({
      contentId: params.contentId,
      contentKind: params.contentKind,
      contentType: params.contentType,
      ucUserId: Taro.getStorageSync('userId')
        ? Taro.getStorageSync('userId')
        : '88888888',
    }).then((res: any) => {
      setData(res);
      setCollect(res.collectStatus);
      // 已下架判断
      if (res.auditStatus === 0) {
        Taro.showToast({ title: '该文章已下架！', icon: 'none' });
        setAuditStatus(true);
        setTimeout(() => {
          Taro.reLaunch({ url: '/pages/home/index' });
        }, 1000);
      } else if (!res.title) {
        setAuditStatus(true);
        Taro.showToast({ title: '该文章已删除！', icon: 'none' });
        setTimeout(() => {
          Taro.reLaunch({ url: '/pages/home/index' });
        }, 1000);
      }
      setLoadingText('');
    });
  };
  useDidShow(() => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });
  useEffect(() => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    //查询内容详情
    queryInfoList();
  }, []);
  //收藏
  const handleCollect = () => {
    if (!clickAble) return;
    clickAble = false;
    setTimeout(() => {
      clickAble = true;
    }, 2000);
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (!isLoginFun()) return;
    //如果以收藏则取消收藏，否则收藏
    if (collect) {
      cancelCollectionFun({
        ucUserId: Taro.getStorageSync('userId'),
        ucLoginPhone: Taro.getStorageSync('mobile'),
        contentId: params.contentId,
        contentKind: params.contentKind,
        contentType: params.contentType,
      }).then((res: any) => {
        showToast('取消收藏成功');
      });
    } else {
      addCollectionFun({
        ucUserId: Taro.getStorageSync('userId'),
        ucLoginPhone: Taro.getStorageSync('mobile'),
        contentId: params.contentId,
        contentKind: params.contentKind,
        contentType: params.contentType,
      }).then((res: any) => {
        showToast('收藏成功');
      });
    }
    setCollect(!collect);
  };
  //跳转到个人中心
  const gotoUserCenter = (item: any) => {
    Taro.navigateTo({
      url: `/subPagesAccount/userCenter/index?contentKind=${item.contentKind}&&contentType=${item.contentType}&&userId=${item.userInfoVo.ucUserId}`,
    });
  };
  //处理分享逻辑
  const handleShare = useCallback(() => {}, []);
  const gotoProductDetail = (data: any) => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.navigateTo({
      url: `/subPagesWiki/cigaDetail/index?sku=${data.cigarSku}`,
    });
  };

  //跳转雪茄柜详情
  const gotoCigaCabinetDetail = (e: any, data: any) => {
    e.stopPropagation(); // 阻止冒泡
    e.preventDefault(); // 防止默认

    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (data && data.productShopPath) {
      halfScreenJump(data.productShopPath, {
        onFail: (err) => {
          //打开失败回调
          Taro.showToast({
            title: '暂无商品信息，请稍后再试',
            icon: 'none',
          });
        },
        onReturn: ({ reason, extraData }) => {
          //关闭半屏回调
          console.log('return reason:', reason, extraData);
        },
      });
    } else {
      Taro.showToast({ title: '暂无商品信息，请稍后再试', icon: 'none' });
    }
  };
  const getImageSrc = useMemo(() => {
    switch (data.userInfoVo && data.userInfoVo.tag) {
      case '品牌方':
        return require('../../assert/imgs/user/pinpai.png');
      case '大咖':
        return require('../../assert/imgs/user/daka.png');
      case '雪茄吧':
        return require('../../assert/imgs/user/xuejiaba.png');
      case '侍咖师':
        return require('../../assert/imgs/user/shikashi.png');
      default: // 包括 null 的情况
        return null;
    }
  }, [data.userInfoVo]);
  return (
    <View
      className="article-detail-container"
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
    >
      <TitleBar showLeftBack={true} title={''}></TitleBar>
      {data && !auditStatus && (
        <View
          className="article-content"
          style={{
            height: `calc(100vh - ${store.commonStore.pageAreaTop}rpx - 112px)`,
          }}
        >
          <View className="article-title">{data.title}</View>
          <View
            className="article-protrait"
            onClick={() => gotoUserCenter(data)}
          >
            <View>
              <Image
                className="protrait-icon"
                src={data && data.userInfoVo && data.userInfoVo.ucAvatarUrl}
              />
            </View>
            <View>
              <Text className="article-protrait-name">
                {data && data.userInfoVo && data.userInfoVo.ucNickname}
              </Text>
              <Image
                className="article-protrait-tag"
                src={data && data.userInfoVo && getImageSrc}
              />
              {/* 品牌方logo和图片 */}
              {/* <Image
              src={
                'https://file.linkcook.cn/image/wineMiniProgram/home/brand.png'
              }
              className="article-brand"
            />
            <Text className="article-brand-name">高希霸品牌</Text> */}
              <View className="article-protrait-date">
                {data.view}浏览·
                {data.publishTime && data.publishTime.split(' ')[0]}
                {data.city ? '·' + data.city : ''}
              </View>
            </View>
          </View>
          <View>
            <RichText
              className="article-desc"
              nodes={formatRichText(data.contentRich)}
            />
          </View>
        </View>
      )}
      {/* 底部分享和收藏 */}
      {data && !auditStatus && (
        <View className="article-footer">
          <View className="at-row">
            <View className="left-btn">
              <Button
                className="custom-share-wrapper"
                openType="share"
                onClick={handleShare}
              >
                <Image
                  className="footer-icon"
                  src={
                    'https://file.linkcook.cn/image/wineMiniProgram/home/share.png'
                  }
                />
              </Button>

              <Button
                openType="share"
                className="footer-text"
                style={{ textAlign: 'left' }}
              >
                分享
              </Button>
            </View>
            <View
              className="left-btn"
              style={{ width: '40px' }}
              onClick={handleCollect}
            >
              <Image
                className="footer-icon"
                src={
                  collect
                    ? 'https://file.linkcook.cn/image/wineMiniProgram/home/collected.png'
                    : 'https://file.linkcook.cn/image/wineMiniProgram/home/uncollect.png'
                }
              />
              <Button className="footer-text">
                {collect ? '已收藏' : '收藏'}
              </Button>
            </View>
            {/* 关联产品 */}
            <View className="right-btn">
              {data.contentCigarVo && data.contentCigarVo.contentCigarZh && (
                <View
                  className="right-product"
                  onClick={() => gotoProductDetail(data.contentCigarVo)}
                >
                  <View
                    className="right-product-icon"
                    style={{ width: '43px', height: '34px' }}
                  >
                    <Image
                      className="footer-icon-product"
                      mode="aspectFill"
                      src={
                        data.contentCigarVo &&
                        data.contentCigarVo.contentCigarImg
                      }
                    />
                  </View>

                  <View className="footer-text clamp1">
                    {data.contentCigarVo &&
                      data.contentCigarVo.contentCigarBrand}
                  </View>
                </View>
              )}
              {data.contentCigarCabinetVo &&
                data.contentCigarCabinetVo.contentCigarCabinetZh && (
                  <View
                    className="right-product"
                    onClick={(e) =>
                      gotoCigaCabinetDetail(e, data.contentCigarCabinetVo)
                    }
                  >
                    <View
                      className="right-product-icon"
                      style={{ width: '43px', height: '34px' }}
                    >
                      <Image
                        className="footer-icon-product"
                        mode="aspectFill"
                        src={
                          data.contentCigarCabinetVo &&
                          data.contentCigarCabinetVo.contentCigarCabinetImg
                        }
                      />
                    </View>
                    <View className="footer-text clamp1">
                      {data.contentCigarCabinetVo &&
                        data.contentCigarCabinetVo.contentCigarCabinetZh}
                    </View>
                  </View>
                )}
            </View>
            <StatusToast />
          </View>
        </View>
      )}
      {(data === null || data === 'null' || auditStatus) && (
        <View className="article-no-data">
          <CommonBlank desc="当前内容无法展示" visible />
        </View>
      )}
    </View>
  );
};

export default observer(ArticleDetail);
